<template>
    <div class="main_clue">
        <!-- 顶部 搜索 -->
        <div class="nvs" v-show="showSearch">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="客户姓名">
                        <el-input v-model="queryInfo.name" placeholder="请输入客户姓名" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="客户手机">
                        <el-input v-model="queryInfo.phone" placeholder="请输入客户手机号码" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="归属人">
                        <el-input v-model="queryInfo.owner" placeholder="请输入线索归属人" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="渠道来源" style="width: 197px;">
                        <el-select v-model="queryInfo.channelId" placeholder="渠道来源">
                            <el-option v-for="(item, index) in channelList" :key="index" :label="item.channelName"
                                :value="item.channelId" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20" style="margin-top: 15px;">
                <el-col :span="6">
                    <el-form-item label="跟进状态">
                        <el-select style="width: 197px;" v-model="queryInfo.status" placeholder="线索状态">
                            <el-option label="已分配" value="0" />
                            <el-option label="伪线索" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="9" style="padding-left: 5px;">
                    <el-form-item label="跟进时间">
                        <el-date-picker v-model="formTime" type="datetimerange" start-placeholder="开始日期" @change="Times"
                            end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd"
                            time-format="A hh:mm:ss" />
                    </el-form-item>
                </el-col>
                <div class="btns">
                    <el-button type="primary" :icon="Search" @click="getClueList">搜索</el-button>
                    <el-button :icon="Refresh" @click="deleQuery">重置</el-button>
                </div>
            </el-row>
        </div>
        <!-- 操作部分 -->
        <div class="Btn">
            <div class="B_tns">
                <el-button type="primary" :icon="Plus" plain @click="showDialog">新增</el-button>
                <el-button type="success" :icon="Edit" plain @click="editDialog"
                    :disabled="isDis.length == 1 ? false : true">修改</el-button>
                <el-button type="danger" :icon="Delete" plain @click="open"
                    :disabled="isDis.length != 0 ? false : true">删除</el-button>
                <el-button type="warning" :icon="Download" plain :disabled="isDis.length != 0 ? false : true"
                    @click="exportToExcelAAAA">导出</el-button>
            </div>
            <div class="ri_tns">
                <el-button :icon="Search" circle @click="toggleSearch" />
                <el-button :icon="Refresh" circle  @click="getClueList"/>
            </div>
        </div>
        <!-- 内容列表部分 -->
        <main>
            <div class="table_box">
                <el-table :data="dataList" style="width: 100%; " border @selection-change="handleSelectionChange"
                    height="450">
                    <el-table-column type="selection" width="55" />
                    <el-table-column fixed prop="clueId" label="线索编码" width="150" />
                    <el-table-column prop="name" label="客户名称" width="120" />
                    <el-table-column prop="phone" label="手机号码" width="120" />
                    <el-table-column prop="channelName" label="渠道来源" width="120" />
                    <el-table-column prop="createTime" label="创建时间" width="200" />
                    <el-table-column prop="owner" label="线索归属" width="120" />
                    <el-table-column label="线索状态" width="120">
                        <template #default="scope">
                            <el-tag type="warning" v-if="scope.row.status == 0">伪线索</el-tag>
                            <el-tag type="primary" v-if="scope.row.status == 1">已分配</el-tag>
                            <el-tag type="warning" v-if="scope.row.status == 2">跟进中</el-tag>
                            <el-tag type="warning" v-if="scope.row.status == 3">回收</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="nextTime" label="下次跟进的时间" width="200" />
                    <el-table-column fixed="right" label="操作" min-width="210">
                        <template #default="scope">
                            <div v-if="scope.row.status == 0">
                                <el-button link type="primary" size="small" :icon="View"
                                    @click="LookView(scope.row)">查看</el-button>
                            </div>
                            <div v-else-if="scope.row.status == 2">
                                <el-button link type="primary" size="small" :icon="View"
                                    @click="LookView(scope.row)">查看</el-button>
                               
                                <el-button link type="primary" size="small" :icon="TopRight"
                                    @click="postView(scope.row)">跟进</el-button>
                            </div>
                            <div v-else>
                                <el-button link type="primary" size="small" :icon="View"
                                    @click="LookView(scope.row)">查看</el-button>
                                <el-button link type="primary" size="small" :icon="Pointer"
                                    @click="openDinao(scope.row)">分配</el-button>
                                <el-button link type="primary" size="small" :icon="TopRight"
                                    @click="postView(scope.row)">跟进</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页器 -->
            <Pagination :total="total" @changePage="setPage" @changeRows="setRows"></Pagination>
        </main>

        <!-- 新增或者编辑的弹框 -->
        <el-dialog v-model="dialogFormVisible" :title="id ? '修改线索' : '新增线索'" width="800">
            <el-form ref="ruleFormRef" style="" :model="ruleForm" :rules="rules" label-width="auto"
                class="demo-ruleForm" :size="formSize" status-icon>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phone">
                            <el-input v-model="ruleForm.phone" aria-placeholder="请输入手机号码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="name" aria-placeholder="请输入客户姓名">
                            <el-input v-model="ruleForm.name" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="渠道来源">
                            <el-select v-model="ruleForm.channelId" placeholder="渠道来源">
                                <el-option v-for="(item, index) in channelList" :key="index" :label="item.channelName"
                                    :value="item.channelId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="活动信息">
                            <el-select v-model="ruleForm.activityId" placeholder="渠道来源">
                                <el-option v-for="(item, index) in activeList" :key="index" :label="item.activityName"
                                    :value="item.activityId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户性别">
                            <el-radio-group v-model="ruleForm.gender">
                                <el-radio value=1 :label=1 size="large">男</el-radio>
                                <el-radio value=0 :label=0 size="large">女</el-radio>
                                <el-radio value=2 :label=2 size="large">未知</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户年龄">
                            <el-input-number v-model="ruleForm.age" :min="1" aria-placeholder="年龄" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="微信号" aria-placeholder="请输入微信号码">
                            <el-input v-model="ruleForm.weixin" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="QQ号码" aria-placeholder="请输入QQ号码">
                            <el-input v-model="ruleForm.qq" />
                        </el-form-item>
                    </el-col>
                </el-row>


            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button v-if="!id" type="success" @click="addData">确认</el-button>
                    <el-button v-else type="primary" @click="editData">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 线索分配 -->
        <el-dialog v-model="dialogVisible" title="无效线索" width="700">
            <el-row :gutter="30">
            <el-col :span="12">
                <el-form-item label="归属部门" >
                    <el-tree-select
                        v-model="valueID"
                        :data="treeData"
                        check-strictly
                        :render-after-expand="true"
                        :props="{ value: 'id', label: 'label',children:'children'}"
                        style="width: 240px"
                         @change="handleChange"
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="分配给" >
                    <el-tree-select
                        v-model="depId"
                        :data="deppList"
                        check-strictly
                        :render-after-expand="true"
                        :props="{ value: 'deptId', label: 'nickName',children:'dept'}"
                        style="width: 240px"
                        @change="handleDeptChange"
                    />
                </el-form-item>
            </el-col>
        </el-row>
              

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="sumbilde">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup lang="ts">
import { Delete, Edit, Search, Refresh, Plus, Download, View, Pointer, TopRight } from '@element-plus/icons-vue'
import { onMounted, reactive, ref, toRefs, watch } from 'vue';
import { clueListData, getData } from '@/api/tienchin/index';
import Pagination from '../Pagination.vue';
import { ComponentSize, ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
const valueID = ref(null);
const isDis = ref([]);
//显示隐藏搜索操作
const showSearch = ref(true);
const toggleSearch = () => {
    showSearch.value = !showSearch.value;
};
const formTime = ref([]);
const Times = () => {
    console.log(formTime.value);
    // console.log(queryInfo.value);

}
import { formdata } from "../hook/format"
let id = 0;//获取线索ID
const queryInfo = ref({
    pageNum: 1,
    pageSize: 10,//最多数据
    name: undefined,
    channelId: undefined,
    phone: undefined,
    owner: undefined,
    createTime: undefined,
    nextTime: undefined
});
watch(formTime, (newVal) => {
    console.log(newVal)
    const formatTimeArray = ref([])
    newVal.forEach(el => {
        // console.log(el)
        formatTimeArray.value.push(formdata.formDate(el))
        queryInfo.value.createTime = formatTimeArray.value[0]
        queryInfo.value.nextTime = formatTimeArray.value[1]

    });
})
//重置查询
const deleQuery = () => {
    queryInfo.value = {
        page: 1,
        pageSize: 10,//最多数据
        name: undefined,
        phone: undefined,
        owner: undefined,
        createTime: undefined,
        nextTime: undefined,
        status: undefined
    };
    getClueList()
}
// 分页器返回参数 通过自定义事件
const setPage = (n: number) => {
    queryInfo.value.pageNum = n;
    getClueList();
};
const setRows = (n: number) => {
    queryInfo.value.pageSize = n;
    getClueList();
};


//渲染全部的数据列表
const dataList = ref([]);
const total = ref(0);
const getClueList = async () => {
    const res: any = await getData(`/tienchin/clue/list`, queryInfo.value);
    console.log(res);
    // 将数据倒序排列
    const reversedRows = res.rows.slice().reverse();

    dataList.value = reversedRows;
    total.value = res.total;
};
const channelList = ref([]);//渠道来源的数据
const getChannel = async () => {//查询渠道来源
    const res: any = await clueListData('/tienchin/clue/channels', '');
    console.log("渠道=》", res);
    channelList.value = res.data.slice(0, 10);
};


onMounted(() => {
    getClueList();
    getChannel();

});

//实现点击添加事件
const dialogFormVisible = ref(false)
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    activityId: null,
    age: 0,//年龄
    channelId: 1,//渠道id
    clueId: 0,
    createBy: "",
    createTime: "",
    delFlag: 0,
    endTime: "",
    failCount: 0,
    gender: 0,//性别
    level: 0,
    name: "",//客户姓名
    nextTime: "",
    phone: "",//手机号码
    qq: "",//QQ号码
    remark: 0,
    status: 0,
    subject: 0,
    transfer: true,
    updateBy: "",
    updateTime: "",
    weixin: ""//微信号码
})
const rules = reactive<FormRules>({
    name: [
        { required: true, message: '客户姓名不能为空', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '手机号码不能为空', trigger: 'blur' },
    ],
    regions: [
        { required: true, message: '请选择渠道来源', trigger: 'change' },
    ],
    activityId: [
        { required: false, message: '请输入活动信息', trigger: 'blur' },
    ],
    gender: [
        { required: true, message: '请选择客户性别', trigger: 'change' },
    ],
    age: [
        { required: true, message: '请输入客户年龄', trigger: 'blur' }
    ],
    weixin: [
        { required: false, message: '请输入微信号', trigger: 'blur' },
    ],
    qq: [
        { required: false, message: '请输入QQ号码', trigger: 'blur' }
    ]
})


//点击显示弹框
const showDialog = () => {
    dialogFormVisible.value = true;
    id = 0;
    getActiveList()
    ruleForm.name = '';
    ruleForm.age = 0;
    ruleForm.gender = '';
    ruleForm.phone = '';
    ruleForm.qq = '';
    ruleForm.weixin = '';
    ruleForm.activityId = 0;
};
const addData = async () => {
    const res: any = await clueListData('/tienchin/clue', ruleForm, 'post');
    if (res.code == "200") {
        console.log("添加", res);
        ElMessage({
            message: '新增成功',
            type: 'success',
        })
        getClueList()
        dialogFormVisible.value = false;
    };
};

//实现多选功能
const multipleSelection = ref([]);//选中的数据
const handleSelectionChange = (val: any) => {
    multipleSelection.value = val;
};
//查询活动信息
const activeList = ref([]);
const getActiveList = async () => {
    const id = ruleForm.channelId;
    const res = await getData('/tienchin/clue/activity/' + id, '');
    console.log('活动=>', res);
    activeList.value = res.data;
};
watch(() => ruleForm.channelId, () => {
    getActiveList()
});
// 修改功能
const editDialog = async () => {
    dialogFormVisible.value = true;
    id = multipleSelection.value[0].clueId;
    const res = await clueListData('/tienchin/clue/summary/' + id, '', 'get');
    if (res.code == "200") {
        console.log('回显==》', res);
        ruleForm.age = res.data.age;
        ruleForm.name = res.data.name;
        ruleForm.gender = Number(res.data.gender);
        ruleForm.phone = res.data.phone;
        ruleForm.qq = res.data.qq;
        ruleForm.weixin = res.data.weixin;
        ruleForm.status = res.data.status;
        ruleForm.clueId = res.data.clueId;
        ruleForm.channelId = res.data.channelId;
        ruleForm.activityId = res.data.activityId;
        ruleForm.status = res.data.status;
        getActiveList()
    }

};
const editData = async () => {
    const res = await clueListData('/tienchin/clue/', ruleForm, 'put');
    if (res.code == "200") {
        console.log(res);
        ElMessage({
            message: '新增成功',
            type: 'success',
        })
        getClueList()
        dialogFormVisible.value = false;
    }
};

//删除功能
const deleteData = async (row) => {
    const res = await clueListData('/tienchin/clue/' + row, '', 'delete');
    if (res.code == "200") {
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
        dialogFormVisible.value = false;
        getClueList()
    }
};
const open = () => {
    const ids = ref('');
    multipleSelection.value.forEach((item: any) => {
        ids.value += item.clueId + ',';
    });
    ElMessageBox.confirm(
        '是否确认删除线索编号为 ' + ids.value + ' 的数据项?',
        'Warning',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            deleteData(ids)
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}
watch(multipleSelection, (newVal) => {
    console.log(newVal);
    let arr = [];
    arr = newVal.map(item => item.clueId)
    isDis.value = arr;
}, { deep: true })


//导出功能
import * as XLSX from 'xlsx';
import { saveAs } from "file-saver";
// 导出到Excel
function exportToExcel() {
    const ws = XLSX.utils.json_to_sheet(multipleSelection.value);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }

    saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'data.xlsx');
}


//*********************************************测试导出表格******【设置表头的数据】**************************************** */
function exportToExcelAAAA() {
    // 定义表头
    const headers = ["索引编码", "客户名称", "手机号码", "渠道来源", "创建时间"]; // 根据实际需求调整表头

    // 获取选中的数据
    const data = multipleSelection.value;
    // console.log("data",data);
    
    // 将数据转换为带有表头的数组
    const dataWithHeaders = [headers].concat(data.map(item => [
        item.clueId,
        item.name,
        item.phone,
        item.channelName,
        item.createTime
    ]));
    // console.log("合并的数据",dataWithHeaders);
    // 创建工作表
    const ws = XLSX.utils.aoa_to_sheet(dataWithHeaders);

    // 创建工作簿
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "线索管理表格");

    // 写入工作簿
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

    // 转换为二进制格式
    function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
    }

    // 保存文件
    saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), '线索管理信息.xlsx');
}

//************************************************************************************************ */





































import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
// 查看按钮点击事件
const LookView = (row: any) => {
    router.push('/clue/info?id=' + row.clueId);
};
const postView = (row: any) => {
    router.push('/clue/info?postid=' + row.clueId);
};
const assignment = reactive(
    {
    assignId: 0,//该条数据
    type: 0,
    departmentId: null,//部门
    nickName: "TienChin健身_test",//子部门
    userId: 2,//子
    userName: "ry",
    deptId: 105
}
)
const depId = ref(null);
const dialogVisible = ref(false);
const treeData = ref([]);
import Cookies from 'js-cookie';
// 定义一个函数来发送GET请求
async function fetchData(url: string, params?: any, headers?: any) {
    try {
        const response = await axios.get(url, {
            params,
            headers: {
                Authorization: 'Bearer ' +Cookies.get('Admin-Token'),
                'Content-Type': 'application/json' // 默认头部
            }
        });
        return response.data;
    } catch (error) {
        console.error('请求出错:', error);
        throw error;
    }
}
async function fetchDataPost(url: string, data?: any, headers?: any) {
    try {
        const response = await axios.post(url, data, {
            headers: {
                Authorization: 'Bearer ' + Cookies.get('Admin-Token'),
                'Content-Type': 'application/json' // 默认头部
            }
        });
        return response.data;
    } catch (error) {
        console.error('请求出错:', error);
        throw error;
    }
}
onMounted(() => {
    fetchData("http://47.104.167.34:9100/prod-api/system/dept/treeselect", {}).then(res => {
        console.log(res); 
        treeData.value = res.data;
    });
});
const openDinao = (id:any) => {
    dialogVisible.value = true;
    assignment.assignId = id.clueId;
};

// 监听选中值变化的事件处理函数
const deppList = ref([]);
const handleChange = (value) => {
    assignment.departmentId = value;
  console.log('选中的值:', value);
  fetchData(`http://47.104.167.34:9100/prod-api/tienchin/clue/users/${value}`, {}).then(res => {
        console.log("分配给==>",res); 
        deppList.value = res.data;
      
    });

};
const handleDeptChange = async(row: any) => {
    console.log(row);
    const arr = deppList.value.filter(item => {
            return item.deptId == row;
        })
        // console.log("ar",arr[0].userId);
        assignment.nickName = arr[0].nickName;
        assignment.userId = arr[0].userId;
        assignment.userName = arr[0].userName;
        assignment.deptId = arr[0].deptId;
};

//确认分配
const sumbilde = async() => {
    console.log(assignment);
    fetchDataPost('http://47.104.167.34:9100/prod-api/tienchin/assignment',assignment).then( res => {
        if(res.code == 200){
        ElMessage({
            message: '分配成功',
            type: 'success',
        });
        dialogVisible.value = false;
    }
})
    
};



</script>

<style lang="scss" scoped>
::v-deep .nvs .el-form-item__label {
    font-weight: 550;
    padding: 0 15px 0 0;
}

::v-deep .nvs .el-input__inner {
    width: 195px;
}

.main_clue {
    padding: 15px;

    // 上方搜索框
    .nvs .el-form-item {
        display: flex;
        align-items: center;
        color: #676465;
    }

    //操作按钮部分
    .Btn {
        display: flex;
        justify-content: space-between;
        padding: 15px 0 10px 0;
    }
}

//抽屉弹框
.el-drawer__body {
    display: flex;
}
</style>